package entity_model.json.deserializers;

import com.google.gson.*;
import entity_model.Entity;
import entity_model.EntityModel;
import entity_model.Relationship;
import utils.titles.Title;

import java.lang.reflect.Type;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* Created by nuno-rafael-figueiredo on 14-05-2014.
*/
public class EntityModelDeserializer implements JsonDeserializer<EntityModel> {

    private static Map<JsonDeserializationContext, EntityModel> cache = new LinkedHashMap<>();

    @Override
    public EntityModel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        EntityModel entityModel = new EntityModel(null);

        cache.put(context, entityModel);

        final JsonObject jsonObject = json.getAsJsonObject();

        entityModel.setTitle(Title.fromLowered(jsonObject.get("name").getAsString()));

        Entity[] entities = context.<Entity[]>deserialize(jsonObject.get("entities"), Entity[].class);

        for (Entity entity : entities)
            entityModel.entities.add(entity);

        Collections.addAll(entityModel.relationships, context.<Relationship[]>deserialize(jsonObject.get("relationships"), Relationship[].class));

        return entityModel;
    }

    public static EntityModel get(JsonDeserializationContext context) {
        return cache.get(context);
    }
}
